package org.bapoint.bawirelessprogressordercenter.config;

import org.bapoint.api.user.feign.WarmUpFeignClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

@Component
public class FeignAutoWarmUpRunner implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(FeignAutoWarmUpRunner.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) {
        log.info("🚀 开始自动预热所有 Feign Client...");

        // 找出所有实现了 WarmUpFeignClient 的 Bean
        Map<String, WarmUpFeignClient> feignClients = applicationContext.getBeansOfType(WarmUpFeignClient.class);

        if (feignClients.isEmpty()) {
            log.warn("未找到任何需要预热的 Feign Client");
            return;
        }

        feignClients.forEach((beanName, client) -> {
            try {
                long start = System.currentTimeMillis();
                String result = client.warmUp(); // 调用预热方法
                long cost = System.currentTimeMillis() - start;
                log.info("✅ Feign Client [{}] 预热成功，耗时: {} ms, 结果: {}",
                        beanName, cost, result);
            } catch (Exception e) {
                log.warn("❌ Feign Client [{}] 预热失败", beanName, e);
            }
        });

        log.info("🏁 所有 Feign Client 预热完成！");
    }
}